package org.tq.security.rsa;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * 
 * @title 		
 * @description	
 * @usage		
 * @company		上海微汇信息技术有限公司
 * @author		TQSUMMER
 * @create		2012-5-25 下午3:46:25
 */
public class CertificatePriPub {
	public static void main(String[] args) throws CertificateException, NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
			KeyStoreException, IOException, UnrecoverableKeyException {
		byte[] msg = "test!中文".getBytes("UTF8"); // 待加解密的消息  

		// 用证书的公钥加密  
		CertificateFactory cff = CertificateFactory.getInstance("X.509");
		FileInputStream fis1 = new FileInputStream("C://MyKeyStore//TestKey2.cer"); // 证书文件  
		Certificate cf = cff.generateCertificate(fis1);
		PublicKey pk1 = cf.getPublicKey(); // 得到证书文件携带的公钥  
		Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 定义算法：RSA  
		c1.init(Cipher.ENCRYPT_MODE, pk1);
		byte[] msg1 = c1.doFinal(msg); // 加密后的数据  

		// 用证书的私钥解密 - 该私钥存在生成该证书的密钥库中  
		FileInputStream fis2 = new FileInputStream("C://MyKeyStore//TestStore");
		KeyStore ks = KeyStore.getInstance("JKS"); // 加载证书库  
		char[] kspwd = "000000".toCharArray(); // 证书库密码  
		char[] keypwd = "000000".toCharArray(); // 证书密码  
		ks.load(fis2, kspwd); // 加载证书  
		PrivateKey pk2 = (PrivateKey) ks.getKey("TestKey2", keypwd); // 获取证书私钥  
		fis2.close();
		Cipher c2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		c2.init(Cipher.DECRYPT_MODE, pk2);
		byte[] msg2 = c2.doFinal(msg1); // 解密后的数据  

		System.out.println(new String(msg2, "UTF8")); // 将解密数据转为字符串  
	}
}
